package com.nengchuan.eic.nceconomy.service;

import com.nengchuan.eic.nceconomy.constant.CategoryEnum;
import com.nengchuan.eic.nceconomy.constant.CommonConstant;
import com.nengchuan.eic.nceconomy.constant.IndexDictErrorEnum;
import com.nengchuan.eic.nceconomy.constant.ProjectEnum;
import com.nengchuan.eic.nceconomy.entity.po.IndexDict;
import com.nengchuan.eic.nceconomy.dao.IndexDictMapper;
import com.nengchuan.eic.nceconomy.entity.vo.IndexDictCodeVO;
import com.nengchuan.eic.nceconomy.entity.vo.IndexListVO;
import com.nengchuan.eic.nceconomy.service.IndexDictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nengchuan.eic.nceconomy.util.ExcelSerialNumUtils;
import com.nengchuan.util.NullCheckUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 指标字典表 服务实现类
 * </p>
 *
 * @author luoping
 * @since 2020-04-23
 */
@Service
public class IndexDictServiceImpl extends ServiceImpl<IndexDictMapper, IndexDict> implements IndexDictService {

    @Autowired
    private IndexDictMapper indexDictMapper;

    @Override
    public List<IndexDict> findByNames(List<String> names) {

        if (NullCheckUtils.isNull(names)) {
            return Collections.emptyList();
        }
        return indexDictMapper.findByNames(names);
    }

    @Override
    public String getByName(String code) {
        return indexDictMapper.getByName(code);
    }

    @Override
    public List<IndexDict> getDetailList(String type) {
        return indexDictMapper.findByType(type);
    }

    /**
     * 查询code
     *
     * @param serialNum    序号
     * @param name         名字
     * @param templateName 模板sheet名
     * @param parentCode   顶级父类的code
     * @return 行列code及错误类型
     */
    @Override
    public IndexDictCodeVO lookUpCode(String serialNum, String name, String templateName, String parentCode, String projectCode, String category) {
        if(StringUtils.isBlank(serialNum)&&StringUtils.isBlank(name)){
            return new IndexDictCodeVO("", IndexDictErrorEnum.SUCCESS.msg, IndexDictErrorEnum.SUCCESS.type, new IndexDict());
        }
        List<IndexDict> indexDicts;
        //行指标
        if (CollectionUtils.isEmpty(CommonConstant.LINEINDEXDICT)) {
            List<IndexDict> lineIndex = indexDictMapper.findByType(CommonConstant.indexType.LINE);
            CommonConstant.LINEINDEXDICT.addAll(lineIndex);
        }
        if (CollectionUtils.isEmpty(CommonConstant.LINEINDEXDICTSETTLE)) {
            List<IndexDict> lineIndex = indexDictMapper.findByTypeSettle(CommonConstant.indexType.LINE);
            CommonConstant.LINEINDEXDICTSETTLE.addAll(lineIndex);
        }
        if (CategoryEnum.SETTLE.code.equals(category)) {
            indexDicts = CommonConstant.LINEINDEXDICTSETTLE;
        } else {
            indexDicts = CommonConstant.LINEINDEXDICT;
        }
        //无父节点   判断名字或序号相同即可
        if (StringUtils.isBlank(parentCode)) {
            IndexDict indexDict = indexDicts.stream()
                    .filter(x -> (x.getName().equals(name) || (StringUtils.isNotBlank(serialNum) && x.getSerialNum().equals(serialNum))) && x.getTemplateName().equals(templateName) && x.getProjectIndex().equals(projectCode)).findFirst().orElse(null);
            if (indexDict == null) {
                return new IndexDictCodeVO(null, IndexDictErrorEnum.NONE.msg, IndexDictErrorEnum.NONE.type, indexDict);
            } else {
                if (indexDict.getSerialNum().equals(serialNum) && indexDict.getName().equals(name)) {
                    return new IndexDictCodeVO(indexDict.getCode(), IndexDictErrorEnum.SUCCESS.msg, IndexDictErrorEnum.SUCCESS.type, indexDict);
                } else if (indexDict.getName().equals(name)) {
                    //序号不匹配
                    if (StringUtils.isBlank(serialNum)) {
                        //序号为空 不用匹配
                        return new IndexDictCodeVO(indexDict.getCode(), IndexDictErrorEnum.SUCCESS.msg, IndexDictErrorEnum.SUCCESS.type, indexDict);
                    }
                    return new IndexDictCodeVO(indexDict.getCode(), IndexDictErrorEnum.SERIAL_DIFF.msg, IndexDictErrorEnum.SERIAL_DIFF.type, indexDict);
                } else {
                    //名称不匹配
                    return new IndexDictCodeVO(indexDict.getCode(), IndexDictErrorEnum.NAME_DIFF.msg, IndexDictErrorEnum.NAME_DIFF.type, indexDict);
                }
            }
        } else {
            //有父节点
            String[] split = parentCode.split("");
            List<String> strings = Stream.of(split).collect(Collectors.toList());
            for (int i = strings.size() - 1; i >= 0; i--) {
                if ("0".equals(strings.get(i))) {
                    strings.remove(i);
                } else {
                    break;
                }
            }
            String join = StringUtils.join(strings, "");
            List<IndexDict> collect = indexDicts.stream()
                    .filter(x -> {
                        if (name.contains("kV")) {
                            String replace = name.replaceAll("\\d+", "**");
                            return (x.getName().equals(replace) || x.getName().equals(name) || (StringUtils.isNotBlank(serialNum) &&x.getSerialNum().equals(serialNum))) && x.getCode().startsWith(join) && x.getTemplateName().equals(templateName) && x.getProjectIndex().equals(projectCode);
                        }
                        return (x.getName().equals(name) || (StringUtils.isNotBlank(serialNum) &&x.getSerialNum().equals(serialNum))) && x.getCode().startsWith(join) && x.getTemplateName().equals(templateName) && x.getProjectIndex().equals(projectCode);
                    }).collect(Collectors.toList());
            if (collect.size() == 0) {
                return new IndexDictCodeVO(null, IndexDictErrorEnum.NONE.msg, IndexDictErrorEnum.NONE.type, null);
            } else if (collect.size() == 1) {
                IndexDict indexDict = collect.get(0);
                if (indexDict.getName().equals(name) && indexDict.getSerialNum().equals(serialNum)) {
                    //完全匹配
                    return new IndexDictCodeVO(indexDict.getCode(), IndexDictErrorEnum.SUCCESS.msg, IndexDictErrorEnum.SUCCESS.type, indexDict);
                } else if (indexDict.getName().equals(name)) {
                    //序号不匹配
                    return new IndexDictCodeVO(indexDict.getCode(), IndexDictErrorEnum.SERIAL_DIFF.msg, IndexDictErrorEnum.SERIAL_DIFF.type, indexDict);
                } else {
                    //无完全匹配
                    if (name.contains("kV")) {
                        String replace = name.replaceAll("\\d+", "**");
                        IndexDict indexDict1 = collect.stream().filter(x -> x.getName().equals(replace)).findFirst().orElse(null);
                        if (indexDict1 != null) {
                            return new IndexDictCodeVO(indexDict1.getCode(), IndexDictErrorEnum.SUCCESS.msg, IndexDictErrorEnum.SUCCESS.type, indexDict);
                        }
                    }
                    //名称不匹配
                    return new IndexDictCodeVO(indexDict.getCode(), IndexDictErrorEnum.NAME_DIFF.msg, IndexDictErrorEnum.NAME_DIFF.type, indexDict);
                }
            } else {
                //有多个结果
                IndexDict indexDict = collect.stream().filter(x -> x.getName().equals(name) && x.getSerialNum().equals(serialNum)).findFirst().orElse(null);
                if (indexDict != null) {
                    //完全匹配
                    return new IndexDictCodeVO(indexDict.getCode(), IndexDictErrorEnum.SUCCESS.msg, IndexDictErrorEnum.SUCCESS.type, null);
                } else {
                    //无完全匹配
                    if (name.contains("kV")) {
                        String replace = name.replaceAll("\\d+", "**");
                        IndexDict indexDict1 = collect.stream().filter(x -> x.getName().equals(replace)).findFirst().orElse(null);
                        if (indexDict1 != null) {
                            return new IndexDictCodeVO(indexDict1.getCode(), IndexDictErrorEnum.SUCCESS.msg, IndexDictErrorEnum.SUCCESS.type, indexDict);
                        }
                    }
                    return new IndexDictCodeVO(null, IndexDictErrorEnum.NONE.msg, IndexDictErrorEnum.NONE.type, indexDict);
                }
            }
        }
    }

    /**
     * 查询列code
     *
     * @param name        名字
     * @param projectCode 项目code  变电和线路
     * @return 行列code及错误类型
     */
    @Override
    public IndexDictCodeVO lookUpRowCode(String name, String projectCode, String category) {
        //列指标
        if (CollectionUtils.isEmpty(CommonConstant.ROWINDEXDICT)) {
            List<IndexDict> lineIndex = indexDictMapper.findByType(CommonConstant.indexType.ROW);
            CommonConstant.ROWINDEXDICT.addAll(lineIndex);
        }
        if (CollectionUtils.isEmpty(CommonConstant.ROWINDEXDICTSETTLE)) {
            List<IndexDict> lineIndex = indexDictMapper.findByTypeSettle(CommonConstant.indexType.ROW);
            CommonConstant.ROWINDEXDICTSETTLE.addAll(lineIndex);
        }
        IndexDict indexDict;
        if (CategoryEnum.SETTLE.code.equals(category)) {
            indexDict = CommonConstant.ROWINDEXDICTSETTLE.stream().filter(x -> x.getName().equals(name) && x.getProjectIndex().equals(projectCode)).findFirst().orElse(null);
        } else {
            indexDict = CommonConstant.ROWINDEXDICT.stream().filter(x -> x.getName().equals(name) && x.getProjectIndex().equals(projectCode)).findFirst().orElse(null);
        }
        if (indexDict == null) {
            return new IndexDictCodeVO(null, IndexDictErrorEnum.NONE.msg, IndexDictErrorEnum.NONE.type, indexDict);
        } else {
            return new IndexDictCodeVO(indexDict.getCode(), IndexDictErrorEnum.SUCCESS.msg, IndexDictErrorEnum.SUCCESS.type, indexDict);
        }
    }

    @Override
    public IndexListVO getIndex(String name) {
        //查询符合条件的指标
        List<IndexDict> indexDicts=indexDictMapper.findByTypeAndName(name,CommonConstant.indexType.LINE);
        List<IndexDict> indexDictSettles=indexDictMapper.findByTypeAndNameSettle(name,CommonConstant.indexType.LINE);
        indexDicts.addAll(indexDictSettles);
        List<IndexListVO.Index> collect = indexDicts.stream().filter(x -> ProjectEnum.POWER_TRANSFORMATION.code.equals(x.getProjectIndex())).map(IndexListVO.Index::new).collect(Collectors.toList());
        List<IndexListVO.Index> collect1 = indexDicts.stream().filter(x -> ProjectEnum.CIRCUIT.code.equals(x.getProjectIndex())).map(IndexListVO.Index::new).collect(Collectors.toList());
        //变电最终结果
        List<IndexListVO.Index> powerIndex=new ArrayList<>();
        //线路最终结果
        List<IndexListVO.Index> circuitIndex=new ArrayList<>();

        //查询每个指标的父节点
        getResultContainParent(collect, powerIndex);
        getResultContainParent(collect1, circuitIndex);

        IndexListVO indexListVO=new IndexListVO();
        indexListVO.setPowerTransformation(powerIndex);
        indexListVO.setCircuit(circuitIndex);
        return indexListVO;
    }


    private void getResultContainParent(List<IndexListVO.Index> collect, List<IndexListVO.Index> powerIndex) {
        collect.forEach(x->{
            String[] split = x.getCode().split("");
            List<String> strings = Stream.of(split).collect(Collectors.toList());
            for (int i = strings.size() - 1; i >= 0; i--) {
                if ("0".equals(strings.get(i))) {
                    strings.remove(i);
                } else {
                    break;
                }
            }
            String join = StringUtils.join(strings, "");
            if(join.length()>3){
                String substring = join.substring(0, join.length() - 2);
                StringBuilder stringBuilder=new StringBuilder();
                stringBuilder.append(substring);
                if(substring.length()<11){
                    for (int i=0;i<11-substring.length();i++){
                        stringBuilder.append("0");
                    }
                }
                //有父节点
                IndexListVO.Index parent = powerIndex.stream().filter(y->y.getSheetName().equals(x.getSheetName())&&y.getCode().equals(stringBuilder.toString())).findFirst().orElse(null);
                if(parent==null){
                    IndexDict indexDict=indexDictMapper.findIndexByCodeAndTemplateSheetName(x.getSheetName(),stringBuilder.toString());
                    if(indexDict==null){
                        indexDict=indexDictMapper.findIndexByCodeAndTemplateSheetNameSettle(x.getSheetName(),stringBuilder.toString());
                    }
                    if(indexDict==null){
                        List<IndexListVO.Index> list=new ArrayList<>();
                        x.setSon(list);
                        powerIndex.add(x);
                    }else {
                        IndexListVO.Index index = new IndexListVO.Index(indexDict);
                        List<IndexListVO.Index> list=new ArrayList<>();
                        list.add(x);
                        x.setPid(index.getId());
                        index.setSon(list);
                        powerIndex.add(index);
                    }
                }else{
                    x.setPid(parent.getId());
                    parent.getSon().add(x);
                }
            }
        });
    }


}
